<!-- 订单 -->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 订单列表 -->
      <el-col :lg="24" :xs="24">
        <el-card shadow="never" class="table-container">
          <template #header>
            <div class="flex-x-between">
              <div>
                <el-button class="ml-3" @click="handleExport">
                  <template #icon><i-ep-download /></template>
                  导出
                </el-button>
              </div>
            </div>
          </template>

          <el-table
            v-loading="loading"
            :data="pageData"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column
              key="id"
              label="编号"
              align="center"
              prop="id"
              width="200"
            />

            <el-table-column
              key="clientUserName"
              label="客户"
              align="center"
              prop="clientUserName"
            />

            <el-table-column
              key="body"
              label="描述"
              align="center"
              prop="body"
            />

            <el-table-column
              key="payMoney"
              label="价钱(元)"
              align="center"
              prop="payMoney"
            />

            <el-table-column
              key="statusDesc"
              label="状态"
              align="center"
              prop="statusDesc"
            />

            <el-table-column label="创建时间" align="center">
              <template #default="scope">
                <text>
                  {{
                    new Date(scope.row.createdAt)
                      .toISOString()
                      .replace("T", " ")
                      .substring(0, 19)
                  }}
                </text>
              </template>
            </el-table-column>

            <el-table-column label="操作" fixed="right" width="160">
              <template #default="scope">
                <el-button
                  v-if="
                    scope.row.refundRequest != 0 &&
                    scope.row.status == 'success'
                  "
                  type="primary"
                  size="small"
                  link
                  @click="handleOpenDialog(scope.row, 'refund')"
                >
                  <!-- <i-ep-edit /> -->
                  退款
                </el-button>
                <el-button
                  type="danger"
                  link
                  size="small"
                  @click="handleOpenDialog(scope.row)"
                >
                  <!-- <i-ep-delete /> -->
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.current"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 订单表单弹窗 -->
    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="编号id" prop="id">
          <el-input disabled v-model="formData.id" />
        </el-form-item>
        <el-form-item label="价钱(元)" prop="payMoney">
          <el-input disabled v-model="formData.payMoney" />
        </el-form-item>
        <el-form-item label="支付类型" prop="payType">
          <el-input disabled v-model="formData.payType" />
        </el-form-item>
        <el-form-item label="状态" prop="statusDesc">
          <el-input disabled v-model="formData.statusDesc" />
        </el-form-item>
        <el-form-item label="appId" prop="appId">
          <el-input disabled v-model="formData.appId" />
        </el-form-item>
        <el-form-item label="描述" prop="body">
          <el-input disabled v-model="formData.body" />
        </el-form-item>
        <!-- <el-form-item label="case类型" prop="caseType">
          <el-input disabled v-model="formData.caseType" />
        </el-form-item> -->
        <el-form-item
          label="服务类型"
          prop="consultationServiceInfo.businessName"
        >
          <el-input
            disabled
            v-model="formData.consultationServiceInfo.businessName"
          />
        </el-form-item>
        <el-form-item
          label="客户名称"
          prop="consultationServiceInfo.clientName"
        >
          <el-input
            disabled
            v-model="formData.consultationServiceInfo.clientName"
          />
        </el-form-item>
        <el-form-item
          label="客户电话"
          prop="consultationServiceInfo.clientPhone"
        >
          <el-input
            disabled
            v-model="formData.consultationServiceInfo.clientPhone"
          />
        </el-form-item>
        <el-form-item
          label="咨询类型"
          prop="consultationServiceInfo.consultationType"
        >
          <el-input
            disabled
            v-model="formData.consultationServiceInfo.consultationType"
          />
        </el-form-item>
        <el-form-item label="律师" prop="consultationServiceInfo.lawyerName">
          <el-input
            disabled
            v-model="formData.consultationServiceInfo.lawyerName"
          />
        </el-form-item>
        <el-form-item label="创建时间" prop="createdAt">
          <el-input disabled v-model="formData.createdAt" />
        </el-form-item>
      </el-form>

      <!-- <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template> -->
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "InstrumentsCategory",
  inheritAttrs: false,
});

import orderAPI, { OrderQuery, OrderForm, OrderVO } from "@/api/order";

const queryFormRef = ref(ElForm);
const userFormRef = ref(ElForm);

const loading = ref(false);
const removeIds = ref([]);
const total = ref(0);
const pageData = ref<OrderVO[]>();
/** 订单查询参数  */
const queryParams = reactive({
  current: 1,
  pageSize: 10,
  clientId: undefined,
  openId: "",
  payType: "",
  status: "",
  refundRequest: undefined,
});

/**  订单弹窗对象  */
const dialog = reactive({
  visible: false,
  title: "",
});

// 订单表单数据
const formData = reactive<OrderForm>({
  id: undefined,
  appId: "",
  body: "",
  caseType: "",
  clientId: "",
  clientIp: "",
  clientUserName: "",
  consultationServiceInfo: "",
  createdAt: "",
  expiredTime: "",
  lawyerId: "",
  lawyerName: "",
  mchId: "",
  notifyUrl: "",
  openId: "",
  payAmount: undefined,
  payMoney: undefined,
  payType: "",
  payWay: "",
  refundReason: "",
  refundRequest: undefined,
  serviceId: "",
  serviceName: "",
  status: "",
  statusDesc: "",
  subject: "",
  successTime: "",
  transactionId: "",
  updateAt: "",
  wxMiniProgramId: "",
});

/** 订单表单校验规则  */
const rules = reactive({
  category: [{ required: true, message: "订单不能为空", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  orderAPI
    .getOrder(queryParams)
    .then((data) => {
      console.log(data, "订单列表");
      pageData.value = data.records;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function handleResetQuery() {
  // queryFormRef.value.resetFields();
  queryParams.current = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开弹窗
 *
 * @param id 订单ID
 */
async function handleOpenDialog(val?: any, flag?: string) {
  if (!flag) {
    dialog.visible = true;
    dialog.title = "订单详情";
    orderAPI.getOrderById(val.id).then((data) => {
      Object.assign(formData, {
        ...data,
        createdAt: new Date(data.createdAt as string)
          .toISOString()
          .replace("T", " ")
          .substring(0, 19),
      });
    });
  } else {
    dialog.title = "退款";
    orderAPI.getOrderRefund(val.id).then(() => {});
  }
}

/** 关闭弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  userFormRef.value.validate((valid: any) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      // orderAPI
      //   .updateInsCategory(formData)
      //   .then(() => {
      //     if (userId) {
      //       ElMessage.success("修改订单成功");
      //     } else {
      //       ElMessage.success("新增订单成功");
      //     }
      //     handleCloseDialog();
      //     handleResetQuery();
      //   })
      //   .finally(() => (loading.value = false));
    }
  });
}, 3000);

/** 删除订单 */
function handleDelete(id?: number) {
  const userIds = [id || removeIds.value].join(",");

  ElMessageBox.confirm("确认删除订单?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      // orderAPI
      //   .deleteInsCategory(userIds)
      //   .then(() => {
      //     ElMessage.success("删除成功");
      //     handleResetQuery();
      //   })
      //   .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

/** 导出用户 */
async function handleExport() {
  try {
    const response = await fetch("http://192.168.1.126/api/pay/order/export", {
      method: "POST",
      credentials: "include",
      body: JSON.stringify(queryParams),
      headers: {
        "Content-Type": "application/json",
      },
    });
    const fileData = await response.blob();
    const fileName = "支付订单";
    const fileType = "application/vnd.ms-excel;charset=UTF-8";
    const blob = new Blob([fileData], { type: fileType });
    const downloadUrl = window.URL.createObjectURL(blob);

    const downloadLink = document.createElement("a");
    downloadLink.href = downloadUrl;
    downloadLink.download = fileName;

    document.body.appendChild(downloadLink);
    downloadLink.click();

    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(downloadUrl);
  } catch (error) {
    console.error("There was a problem with your fetch operation:", error);
  }
}
onMounted(() => {
  handleQuery();
});
</script>
